package com.iot.mqtt.service.Impl;

import com.iot.mqtt.service.MqttService;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.stereotype.Service;

@Service("MqttServiceImpl")
public class MqttServiceImpl implements MqttService {
    public static final String MQTT_BROKER_HOST = "tcp://47.104.242.242:1883";
    public static final String MQTT_CLIENT_ID = "cloud_service";
    private static final String userName = "admin";
    private static final String password = "public";
    private static MqttAsyncClient client;


    public static void connectMqtt(){
        // 推送消息
        try {
            client = new MqttAsyncClient(MQTT_BROKER_HOST, MQTT_CLIENT_ID, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(userName);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);
            options.setAutomaticReconnect(true);
            client.connect(options,(Object)null,new IMqttActionListener(){
                public void onSuccess(IMqttToken var1){
                    subDevice();
                    System.out.println("连接成功");
                }

                public void onFailure(IMqttToken var1, Throwable var2){

                }
            });
        } catch (Exception e) {
            System.out.println("连接错误");
        }
    }

    public static void sendToDevice(String sendTopic,String sendMsg){
        // 推送消息
        MqttMessage message = new MqttMessage();
        try {
            message.setQos(1);
            message.setRetained(false);
            message.setPayload(sendMsg.getBytes());
            sendTopic = sendTopic.substring(1);
            client.publish(sendTopic,message);
            System.out.println("向设备发送消息, topic:"+sendTopic+", content:"+sendMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void subDevice(){
        try {
            // 订阅
            client.subscribe("sys/#", 0);
            //client.subscribe("ota/#", 0);
            // 设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    System.out.println("connectionLost");
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    try {
                        String[] topics = s.split("/");
                        AliCloudImpl.sendMsg(topics[2]+"_"+topics[1],s,mqttMessage.toString());
                    }catch (Exception e){
                        System.out.println(e.getCause());
                    }
                    System.out.println("向阿里云平台发送消息，Topic: " + "/"+s + " Message: " + mqttMessage.toString());
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}
